package com.guigu.userservice.controller;

import com.guigu.common.utils.R;
import com.guigu.userservice.entity.Role;
import com.guigu.userservice.service.RolePermissionService;
import com.guigu.userservice.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 角色表（用于RBAC权限控制） 前端控制器
 * </p>
 *
 * @author janecraft
 * @since 2025-09-27
 */
@RestController
@RequestMapping("/user/role")
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @GetMapping("/selectRoleById/{id}")
    public Role selectRoleById(@PathVariable("id") Integer id){
        return roleService.getById(id);
    }

    @GetMapping("/selectRoleList")
    public R selectRoleList(){
        List<Role> roleList = roleService.selectRoleList();
        return R.ok().data("roleList", roleList);
    }

    @PostMapping("/addRole")
    public R addRole(@RequestBody Role role){
        roleService.save(role);
        Long newRoleId = role.getRoleId();
        for (Long id: role.getPermission()) {
            rolePermissionService.addRolePermission(newRoleId, id);
        }
        return R.ok();
    }

    @PutMapping("/updateRole")
    public R updateRole(@RequestBody Role role){
        role.setUpdateTime(LocalDateTime.now());
        boolean update = roleService.updateById(role);
        rolePermissionService.deleteRolePermissionByRoleId(role.getRoleId());
        for (Long id: role.getPermission()) {
            rolePermissionService.addRolePermission(role.getRoleId(), id);
        }
        if (update){
            return R.ok();
        }else {
            return R.error();
        }
    }

}
